package com.canto.access.component;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 动态权限决策管理器，判断是否有权限
 *
 * @author jsryin
 * @version 2021-07-02
 */
public class DynamicAccessDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        if (CollectionUtils.isEmpty(collection)) {
            //接口未被配置资源时直接放行
            return;
        }

//        for (ConfigAttribute configAttribute : collection) {
//            //将访问所需资源或用户拥有资源进行比对
//            String needAccess = configAttribute.getAttribute();
//            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
//                if (StringUtils.equals(needAccess, grantedAuthority.getAuthority())) {
//                    return;
//                }
//            }
//        }

        //将访问所需资源或用户拥有资源进行比对，得出可以访问的资源数
        long needCount = collection.parallelStream()
                .filter(attr ->
                        authentication.getAuthorities().stream()
                                .map(GrantedAuthority::getAuthority).collect(Collectors.toSet()).contains(attr.getAttribute())
                ).count();
        if (needCount <= 0) {
            throw new AccessDeniedException("抱歉，您没有访问权限！");
        }

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
